package com.xq.shop.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xq.shop.po.Receiver;
import com.xq.shop.po.User;
import com.xq.shop.service.user.IReceiverService;
import com.xq.shop.util.Const;
import com.xq.shop.util.GsonUtil;
import com.xq.shop.util.RespUtil;
import com.xq.shop.util.UserServiceFactory;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.SearchObject;
import com.xq.shop.vo.RespMsg.Result;
import com.xq.shop.vo.SearchValue.Pattern;

@Controller
@RequestMapping("/user/")
public class ReceiverCtrl extends BaseCtrl<Receiver> {

	private IReceiverService receiverService  = UserServiceFactory.getReceiverService();
	
	@Override
	public IReceiverService getService() {
		return receiverService;
	}
	
	@RequestMapping("receiver_save")
	public ModelAndView save(User user, HttpServletResponse response){
		return null;
	}

	@RequestMapping("receiver_list.do")
	@ResponseBody
	public String list(SearchObject search, HttpServletRequest request){
		User user = (User) request.getSession().getAttribute(Const.User_Session);
		search.addCondition("user_id", user.getId(), Pattern.EQUAL);
		return super.list(search, request);
	}

	@RequestMapping("receiver_edit.do")
	public ModelAndView edit(String id){
		return super.edit(id, new ModelAndView("user/receiver_edit"));
	}

	@RequestMapping("receiver_save.do")
	public ModelAndView save(Receiver instance, ModelAndView view, HttpServletRequest request) {
		
		User user = (User) request.getSession().getAttribute(Const.User_Session);
		if(instance.getId() == null || instance.getId() == 0){
			
			instance.setUser_id(user.getId());
			getService().save(instance);
		} else {
			
			Receiver receiver = getService().get(instance.getId());
			
			if(receiver.getUser_id() != user.getId()){
				
			} else {
				getService().update(instance);
			}
		}
		
		return new ModelAndView("user/receiver_list");
	}
	
	@RequestMapping("receiver_delete.do")
	public void delete(String id, HttpServletRequest request, HttpServletResponse response){
		
		User user = (User) request.getSession().getAttribute(Const.User_Session);
		getService().delete(Long.parseLong(id), user.getId());
		RespUtil.renderJson(GsonUtil.toJson(new RespMsg(Result.success, "删除成功")), response);
	}
}
